package com.fd.wpx.sso.web.interceptor;

import com.fd.wpx.common.utils.JsonUtils;
import com.fd.wpx.sso.web.annotation.SameUrlData;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 防止表单重复提交的拦截器
 */
public class SameUrlDataInterceptor extends HandlerInterceptorAdapter {
    @Value("${tokenName}")
    private String tokenName;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            SameUrlData annotation = method.getAnnotation(SameUrlData.class);
            if (annotation != null) {
                if(repeatDataValidator(request))
                    //如果重复相同数据,拦截
                    return false;
                else
                    return true;
            }
            return true;
        }else
        {
            return super.preHandle(request, response, handler);
        }

    }
    /**
     * 验证同一个url数据是否相同提交  ,相同返回true
     * @param httpServletRequest
     * @return
     */
    public boolean repeatDataValidator(HttpServletRequest httpServletRequest)
    {

        String params=JsonUtils.objectToJson(httpServletRequest.getParameterMap());
        String url=httpServletRequest.getRequestURI();
        Map<String,String> map=new HashMap<String,String>();
        map.put(url, params);
        String nowUrlParams=map.toString();
        Session session=SecurityUtils.getSubject().getSession();
        Object preUrlParams=session.getAttribute(tokenName);
        if(preUrlParams==null)//如果上一个数据为null,表示还没有访问页面
        {
            session.setAttribute(tokenName, nowUrlParams);
            return false;
        }else //如果已经访问过页面
        {
            if(preUrlParams.toString().equals(nowUrlParams))
            {
                //如果上次url+数据和本次url+数据相同，则表示重复添加数据
                return true;
            }
            else//如果上次 url+数据 和本次url加数据不同，则不是重复提交
            {
                session.setAttribute(tokenName, nowUrlParams);
                return false;
            }

        }
    }
}
